<template>
  <div>
    <el-dialog :visible="isShow" width="600px" class="register" :show-close="false">
      <div class="register-title" slot="title">用户注册</div>
      <!-- el-form
      model--值绑定
      rules--限制条件
      label-width--标题宽度
      el-form-item
              label="标签"
              prop="需要验证的key"
     
      表单验证
      1在开头加model  rules:规则绑定
      验证规则prop[
      {required:true,message:"错误信息"， trigger：”change}]
      
      全局验证
      调用el-form的方法-
      1在el-form上增加ref
      2this.$refs.子组件名。方法
      ->
      -->
      <el-form ref="form" :model="form" label-width="100px" :rules="rules">
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            name="image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item prop="username" label="用户名">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input :show-password="true" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="手机">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item prop="code" label="图形码">
          <el-row>
            <el-col :span="15">
              <el-input v-model="form.code"></el-input>
            </el-col>
            <el-col :span="8" :offset="1">
              <img @click="getcode" class="register-code" :src="codeimg" alt />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="rcode" v-if="bol" label="验证码">
          <el-row>
            <el-col :span="15">
              <el-input v-model="form.rcode"></el-input>
            </el-col>
            <el-col :span="8" :offset="1">
              <el-button @click="getrcode" :disabled="totaltime<5">
                获取用户验证码
                <span v-if="totaltime!=5">({{totaltime+1}}秒)</span>
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div class="register-footer" slot="footer">
        <el-button @click="isShow=false">取消</el-button>
        <el-button @click="submit" type="primary">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getrcode, registeruser } from "@/api/login.js";
export default {
  // 成功后清除页面的注册信息
  // 当isShow为falses,开始清理
  watch: {
    // 先this.,改为双引号
    isShow(newval) {
      if (newval == false) {
        // resetfields表单重置听话
        // this.form = {
        //   avatar: "",
        //   username: "",
        //   phone: "",
        //   email: "",
        //   password: "",
        //   rcode: "",
        //   code: ""
        // };
        this.$refs.form.resetFields();
        // 使用者方法的前提是为form绑定的Prop属性
        // 补一个清除头像的变量
        this.imageUrl = "";
      }
    }
  },
  data() {
    return {
      bol: "true",
      totaltime: 5,
      uploadUrl: process.env.VUE_APP_URL + "/uploads",
      imageUrl: "",
      codeimg: process.env.VUE_APP_URL + "/captcha?type=sendsms",
      isShow: false,
      form: {
        avatar: "",
        username: "",
        phone: "",
        email: "",
        password: "",
        rcode: "",
        code: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入正确用户名", trigger: "change" },
          { min: 3, max: 5, message: "请输入正确用户名", trigger: "change" }
        ],
        phone: [
          {
            required: true,
            message: "请输入正确电话号码",
            trigger: "change"
          },
          {
            validator: (rule, value, callback) => {
              let _reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (_reg.test(value)) {
                callback();
              } else {
                callback(new Error("手机的格式不对，重新输入"));
              }
            },
            trigger: "change"
          }
        ],
        email: [
          {
            required: true,
            message: "请输入正确邮箱",
            trigger: "change"
          },
          {
            validator: (rule, value, callback) => {
              let _reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (_reg.test(value)) {
                callback();
              } else {
                callback(new Error("邮箱的格式不对，重新输入"));
              }
            },
            trigger: "change"
          }
        ],
        avatar: [
          {
            required: true,
            message: "请输入正确",
            trigger: "change"
          }
        ],
        password: [
          {
            required: true,
            message: "请输入正确密码",
            trigger: "change"
          }
        ],
        rcode: [
          {
            required: true,
            message: "请输入正确验证码",
            trigger: "change"
          }
        ],
        code: [
          {
            required: true,
            message: "请输入正确图形码",
            trigger: "change"
          }
        ]
      }
    };
  },
  methods: {
    submit() {
      this.$refs.form.validate(resulte => {
        if (resulte) {
          registeruser(this.form).then(res => {
            window.console.log("注册信息" + res);
            // 公司的全局状态码
            // if (res.data.code == 200) {
              this.$message.success("注册通过");
              // 弹窗关闭
              this.isShow = false;
            // }
          });
        } else {
          this.$message.error("验证失败");
        }
      });
    },

    // 点击重新调用
    getcode() {
      this.codeimg =
        process.env.VUE_APP_URL +
        "/captcha?type=sendsms&erew=" +
        Math.random() * 20;
      //  Date.now();
      // this.bol = false;
      // this.$nextTick();
      // this.bol = true;
    },

    getrcode() {
      // 先确认图形码和手机号都正常输入
      // 调用el-form子组件的validatefield方法，第一参数（数组）是需要验证的字段名/参数
      // 错误信息，空则验证通过，不为空即 不通过

      // 新问题，频繁点击导致开启多个定时器
      // 解决方法---调用前做一个判断

      this.totaltime--;
      let _interval = setInterval(() => {
        this.totaltime--;
        if (this.totaltime <= -1) {
          clearInterval(_interval);
          this.totaltime = 5;
        }
      }, 1000);
      let num = 0;
      this.$refs.form.validateField(["phone", "code"], errorMessage => {
        window.console.log(errorMessage);
        if (errorMessage == "") {
          num++;
        }
      });
      if (num == 2) {
        // 传cookie,不跨域的时候自动带，跨域的时候
        getrcode({ 
          code: this.form.code, 
          phone: this.form.phone 
          }).then(res => {
          window.console.log(res);
          // if (res.data.code == 200) {
            this.$message.success(res.data.captcha + "");
          // } else {
            // alert("失败");
          // }
        });
        // this.$message("验证通过");
      } else {
        this.$message.error("验证不通过");
      }
    },

    // 上传成功
    handleAvatarSuccess(res) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      // this.form.avatar = res.data.file_path;
      // 认为触发avatar的表单验证
      // 调用子组件字典的validatafield方法---
      // 参数为数组、字符串，后面借回调函数，error为空，即验证通过，有则提
      // 后面的回调函数可以不写

      // this.imageUrl = "http://127.0.0.1/heimamm/public/" + res.data.file_path;

      this.form.avatar = res.data.file_path;

      this.$refs.form.validateField(["avatar"]);

      this.imageUrl = process.env.VUE_APP_URL + "/" + res.data.file_path;
    },

    // 上传限制
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG,NPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>

<style lang="less">
.register {
  .el-dialog__header {
    padding: 0;
  }
  .register-title {
    height: 53px;
    line-height: 53px;
    text-align: center;
    color: white;
    background: linear-gradient(to right, #1494fa, #01c6fa);
  }
  .register-footer {
    text-align: center;
  }
  .avatar-uploader {
    margin: 0 auto;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .register-code {
    width: 100%;
    height: 40px;
  }
}
</style>